#ifndef LENSTRAYBUFFER_H
#define LENSTRAYBUFFER_H

#include "AxisModule/singleaxis.h"
#include "CompositeElement/sccylinder.h"
#include "errorHandling/kicktrayerror.h"
#include "lenstraymagazine.h"
#include "namedefinition.h"
#include "systemCore/worker.h"

class LTBufferDetectTrayError : public KickTrayError
{
public:
    LTBufferDetectTrayError()
        : KickTrayError(
            WorkerName::LensTrayBuffer,
            QObject::tr("LensTray弹夹推出Tray,但LensTrayBuffer未检测到Tray!\r\n选项解释: ReKick-重新推Tray, "
                        "Retry: 重新检测, Skip: 跳过此Tray"))
    {
        appendErrorHandlingOption(Skip_);
    }
    // SilicolError interface
protected:
    virtual void implemented() override {}
};

class LensTrayBuffer : public Worker
{
    Q_OBJECT

public:
    explicit LensTrayBuffer(LensTrayModuleConfig *ltConfig,
                            LensTrayModuleState *ltState,
                            LensTrayMagazine *ltMag,
                            QObject *parent = nullptr);

    bool isGettingNewTray() const
    {
        return m_isGettingNewTray;
    }

    // Worker interface
protected:
    virtual void initEventHandle() override;
    virtual void startEventHandle(const WorkerEvent &event) override;
    virtual void stopEventHandle() override {}
    virtual void allWorkerStopped() override;
    virtual void purgeEventHandle() override;
    virtual void resetEventHandle() override;
    virtual void homeWorker(bool moveToReadyPosAfterHome) override;

    // 自动运行逻辑
public slots:
    void getNewTray();
    void ltMagArrivedNextRawTrayPos();
    void ltMagStopped();

    // 手动调试操作
public slots:
    void manuallyGetNewTray(bool showTip = true);
    void synchronizeHasTray();

private:
    bool detectReallyHasTray();
    void getNewTrayImpl();
    void handleStop();

private:
    LensTrayModuleConfig *ltConfig;
    LensTrayModuleState *ltState;
    LensTrayMagazine *ltMag;

    SCAxis::Direction beltRunDir;

    SCDI *ltBufferLeftTraySensor;
    SCDI *ltBufferRightTraySensor;
    SingleAxis *ltBufferBeltZ;
    SCAxis *ltBufferBelt;

    bool hasSynchronizeHasTray = false;
    bool isLTMagArrivedNextRawTrayPos;
    bool m_isGettingNewTray = false;
    bool isLtMagStopped = false;
};

#endif    // LENSTRAYBUFFER_H
